<template>
  <div class="user-tags-container">
    <div class="search-bar">
      <div class="search-input">
        <span class="label">标签名称</span>
        <el-input
          v-model="searchQuery"
          placeholder="请输入内容"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        />
      </div>
      <div class="button-group">
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleSearch">检索</el-button>
        <el-button type="danger" @click="handleAddTag">新建标签</el-button>
      </div>
    </div>

    <el-table
      :data="displayTags"
      style="width: 100%"
      border
    >
      <el-table-column
        prop="name"
        label="标签名称"
        min-width="200"
      >
        <template #default="{ row }">
          <el-tag
            :type="getTagType(row.color)"
            effect="light"
            class="tag-item"
          >
            {{ row.name }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="status"
        label="状态"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.status }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="100"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <div class="pagination-info">
        当前条件共检索到 {{ filteredTags.length }} 条相关信息
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2, 5, 10, 20]"
        :total="filteredTags.length"
        layout="prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="tagForm"
        :rules="rules"
        ref="tagFormRef"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name" required>
          <el-input v-model="tagForm.name" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="tagForm.description" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="颜色" required prop="color">
          <div class="color-options">
            <div
              v-for="color in colorOptions"
              :key="color.value"
              class="color-item"
              :class="{ active: tagForm.color === color.value }"
              @click="selectColor(color.value)"
            >
              <el-tag
                :type="color.type"
                effect="plain"
                class="tag-preview"
              >
                标签
              </el-tag>
              <el-icon v-if="tagForm.color === color.value" class="check-icon">
                <Check />
              </el-icon>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="状态" required prop="status">
          <div class="status-options">
            <div
              class="status-item"
              :class="{ active: tagForm.status === '启用' }"
              @click="tagForm.status = '启用'"
            >
              启用
            </div>
            <div
              class="status-item"
              :class="{ active: tagForm.status === '禁用' }"
              @click="tagForm.status = '禁用'"
            >
              禁用
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check } from '@element-plus/icons-vue'

// 标签数据
const STORAGE_KEY = 'userTagsList'
function loadTags() {
  const local = localStorage.getItem(STORAGE_KEY)
  if (local) {
    try {
      return JSON.parse(local)
    } catch {
      return []
    }
  }
  return [
    { id: 1, name: '优质客户', description: '', color: 'red', status: '正常', userCount: 156, createTime: '2024-01-15 10:00:00' },
    { id: 2, name: '星级客户', description: '', color: 'blue', status: '正常', userCount: 89, createTime: '2024-01-15 10:30:00' },
    { id: 3, name: '多社区', description: '', color: 'purple', status: '正常', userCount: 45, createTime: '2024-01-15 11:00:00' },
    { id: 4, name: '星级客户', description: '', color: 'blue', status: '正常', userCount: 78, createTime: '2024-01-15 11:30:00' }
  ]
}
const tagList = ref(loadTags())
watch(tagList, (val) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(val))
}, { deep: true })

// 搜索相关
const searchQuery = ref('')
const filteredTags = computed(() => {
  if (!searchQuery.value) return tagList.value
  return tagList.value.filter(tag => 
    tag.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const displayTags = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTags.value.slice(start, end)
})

// 颜色选项
const colorOptions = [
  { value: 'red', type: 'danger' },
  { value: 'blue', type: 'primary' },
  { value: 'green', type: 'success' },
  { value: 'gray', type: '' }
]

// 颜色映射函数
const getTagType = (color: string): string => {
  if (color === 'red') return 'danger'
  if (color === 'blue') return 'primary'
  if (color === 'green') return 'success'
  if (color === 'gray') return ''
  return 'primary'
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
// 修改表单数据结构
const tagForm = ref({
  id: null as number | null,
  name: '',
  description: '',
  color: 'red',
  status: '启用'
})
const tagFormRef = ref()
// 修改表单规则
const rules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择标签状态', trigger: 'change' }
  ]
}

// 选择颜色
const selectColor = (color: string) => {
  tagForm.value.color = color
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理重置
const handleReset = () => {
  searchQuery.value = ''
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 处理新建标签
const handleAddTag = () => {
  dialogTitle.value = '新建标签'
  tagForm.value = {
    id: null,
    name: '',
    description: '',
    color: 'red',
    status: '启用'
  }
  dialogVisible.value = true
}

// 处理编辑标签
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑标签'
  tagForm.value = {
    id: row.id,
    name: row.name,
    description: row.description || '',
    color: row.color || 'red',
    status: row.status
  }
  dialogVisible.value = true
}

// 处理提交
const handleSubmit = async () => {
  if (!tagFormRef.value) return
  
  await tagFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (tagForm.value.id === null) {
        // 新建标签
        const newTag = {
          id: tagList.value.length + 1,
          name: tagForm.value.name,
          description: tagForm.value.description,
          color: tagForm.value.color, // 保存颜色
          status: tagForm.value.status,
          userCount: 0,
          createTime: new Date().toLocaleString()
        }
        tagList.value.push(newTag)
        ElMessage.success('新建标签成功')
      } else {
        // 编辑标签
        const tag = tagList.value.find(t => t.id === tagForm.value.id)
        if (tag) {
          tag.name = tagForm.value.name
          tag.description = tagForm.value.description
          tag.color = tagForm.value.color // 保存颜色
          tag.status = tagForm.value.status
          ElMessage.success('编辑标签成功')
        }
      }
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.user-tags-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.search-bar {
  padding: 24px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

.search-input {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.search-input .label {
  width: 80px;
  color: #606266;
}

.search-input .el-input {
  width: 240px;
}

.button-group {
  padding-left: 80px;
}

.button-group .el-button {
  margin-right: 12px;
}

.tag-item {
  margin-right: 8px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

:deep(.el-table) {
  margin: 16px 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-tag) {
  border-radius: 2px;
}

:deep(.el-button--primary.is-link) {
  color: #409eff;
}

:deep(.el-button--primary.is-link:hover) {
  color: #66b1ff;
}

.color-options {
  display: flex;
  gap: 16px;
}

.color-item {
  position: relative;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
}

.color-item.active {
  background-color: #f5f7fa;
}

.tag-preview {
  min-width: 48px;
  text-align: center;
}

.check-icon {
  position: absolute;
  top: -4px;
  right: -4px;
  color: #409eff;
  font-size: 16px;
}

.status-options {
  display: flex;
  gap: 16px;
}

.status-item {
  padding: 5px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  color: #606266;
}

.status-item.active {
  border-color: #f56c6c;
  color: #f56c6c;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-form-item__label::before) {
  margin-right: 2px !important;
}
</style> 